package com.source.thread.aa;

public class ProductorAndCOnsumer {
    public static void main(String[] args) {
        Data data =new Data();

        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Productor-AA").start();



        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Consumer-AA").start();



        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Productor-BB").start();



        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Consumer-BB").start();

    }
}


class   Data{

    private  int  num =0;

    public synchronized void increment() throws InterruptedException {
        while(num!=0){   //  为什么不用if 判断。。。。。。。。。。。。。。。。。。。。。。
            this.wait();
        }
        num++;
        this.notifyAll();
        System.out.println("上产者为"+Thread.currentThread().getName()+"=>"+num);

    }

    public  synchronized  void decrement() throws InterruptedException {

         while(num==0){
             this.wait();
         }
         num--;
         System.out.println("消费者为"+Thread.currentThread().getName()+"=>"+num);
         this.notifyAll();
    }
}
